<template>
  <div v-loading="pageLoading" element-loading-text="加载中...">
    <el-form :model="bookForm" label-width="100px" ref="bookFormDom">
      <el-form-item v-if="selectedTypes.includes('book')" label="图书种类" prop="bookType"
        class="mb-2 flex items-center text-sm">
        <el-row class="mb-4">
          <el-button v-for="item in bookTypes" :key="item" size="large" :type="selectedBookType === item ? 'primary' : ''"
            @click="updateBookType(item)">
            {{ item }}
          </el-button>
        </el-row>
      </el-form-item>

      <el-form-item label="ISBN" prop="isbn">
        <el-input v-model="bookForm.isbn" @keyup.enter="checkBookExists" />
      </el-form-item>
      <el-form-item label="书名" prop="title">
        <el-input v-model="bookForm.title" ref="titleInput" />
      </el-form-item>

      <el-form-item v-if="selectedBookType == '课外书'" label="作者" prop="author">
        <el-input v-model="bookForm.author"></el-input>
      </el-form-item>

      <el-form-item v-if="selectedBookType == '课外书'" label="出版社" prop="publisher">
        <el-input v-model="bookForm.publisher"></el-input>
      </el-form-item>

      <el-form-item v-if="selectedBookType == '杂志'" label="出版月份" prop="publishMonth">
        <el-date-picker v-model="bookForm.publishMonth" type="month" placeholder="请选择出版月份" />
      </el-form-item>

      <div style="display: flex;">
        <el-form-item v-if="selectedBookType === '教辅' && !pageLoading" label="科目" prop="subject">
          <el-select 
            v-model="bookForm.subject" 
            placeholder="请选择科目" 
            style="width: 240px"
            :disabled="pageLoading"
          >
            <el-option 
              v-for="option in subjects" 
              :key="option" 
              :label="option" 
              :value="option"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item v-if="selectedBookType === '教辅' && !pageLoading" label="第几册" prop="grade">
          <el-select 
            v-model="bookForm.grade" 
            placeholder="请选择第几册" 
            style="width: 240px"
            :disabled="pageLoading"
          >
            <el-option 
              v-for="item in grades" 
              :key="item" 
              :label="item" 
              :value="item" 
            />
          </el-select>
        </el-form-item>
      </div>

      <el-form-item label="数量" size="large" prop="quantity">
        <el-input-number v-model="bookForm.quantity" :min="1"></el-input-number>
      </el-form-item>
      <el-form-item label="定价" size="large" prop="price">
        <el-input-number v-model="bookForm.price" type="number" :precision="2" :step="0.01" min="0"
          controls-position="right" placeholder="请输入定价"></el-input-number>
      </el-form-item>
      <el-form-item label="进货折扣" prop="purchaseDiscount">
        <el-input-number 
          v-model="bookForm.purchaseDiscount" 
          :min="0.01" 
          :max="1" 
          :precision="2"
          :step="0.01"
          controls-position="right"
        />
      </el-form-item>
      <el-form-item label="零售折扣" prop="salesDiscount">
        <el-input-number 
          v-model="bookForm.salesDiscount" 
          :min="0.01" 
          :max="1" 
          :precision="2"
          :step="0.01"
          controls-position="right"
        />
      </el-form-item>
      <el-form-item label="进货渠道" prop="channel">
        <el-select 
          v-model="bookForm.channel" 
          placeholder="请选择进货渠道" 
          style="width: 240px"
          :loading="isLoading"
          v-if="!isLoading"
        >
          <el-option 
            v-for="dealer in dealers" 
            :key="dealer.id" 
            :label="dealer.name" 
            :value="dealer.name"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="入库日期" prop="date">
        <el-date-picker type="date" placeholder="选择日期" v-model="bookForm.date" style="width: 100%;"
          :default-value="new Date()"></el-date-picker>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="submitForm('bookForm')">提交</el-button>
        <el-button @click="resetForm('bookForm')">重置</el-button>
      </el-form-item>

      <el-dialog v-model="dialogVisible" title="添加库存">
        <div>
          <p>该书籍已录入：</p>
          <p>书名：{{ existingBook.title }}</p>
          <p>当前库存：{{ existingBook.quantity }}</p>
          <el-form-item label="再添加多少本">
            <el-input-number v-model="additionalQuantity" :min="1"></el-input-number>
          </el-form-item>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitAdditionalQuantity">确认</el-button>
        </span>
      </el-dialog>

    </el-form>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed, nextTick } from 'vue';
import { useStore } from 'vuex';
import { bookTypes } from '@/cfg/config.js';
import { ElMessage } from 'element-plus';
import BookService from '@/api/bookService';
import DealerService from '@/api/dealerService';

// 定义 localStorage key
const STORAGE_KEY = 'bookInventoryForm';

// 从 localStorage 获取保存的表单数据
const getSavedFormData = () => {
  const savedData = localStorage.getItem(STORAGE_KEY);
  if (savedData) {
    return JSON.parse(savedData);
  }
  return null;
};

const store = useStore();

// 从 Vuex store 获取数据
const subjects = computed(() => store.getters['inventory/getSubjects']);
const grades = computed(() => store.getters['inventory/getGrades']);
const dealers = ref([]);
const pageLoading = ref(true); // 添加页面级别的 loading
const isLoading = ref(true); // Select 组件的 loading

const bookForm = reactive({
  title: '',
  author: '',
  isbn: '',
  publisher: '',
  grade: '',
  subject: '',
  date: new Date(),
  quantity: 1,
  price: 0,
  purchaseDiscount: 0.5,  // 默认50%折扣
  salesDiscount: 0.65,    // 默认65%折扣
  channel: '',  // 保持字段名不变，但实际存储经销商名称
});

const selectedTypes = ref(['book']);
const selectedBookType = ref('教辅');
const bookFormDom = ref(null);
const titleInput = ref(null);

const dialogVisible = ref(false);
const existingBook = ref({});
const additionalQuantity = ref(1);

// 获取经销商列表
async function fetchDealers() {
  isLoading.value = true;
  try {
    const response = await DealerService.getAllDealers('book'); // 只获取图书经销商
    dealers.value = response.data;
  } catch (error) {
    console.error("获取经销商列表失败:", error);
    ElMessage.error('获取经销商列表失败');
  } finally {
    isLoading.value = false;
  }
}

onMounted(async () => {
  pageLoading.value = true; // 开始加载
  try {
    // 先获取经销商数据
    await fetchDealers();
    
    // 加载保存的表单数据
    const savedData = getSavedFormData();
    if (savedData) {
      // 更新图书类型
      if (savedData.type) {
        selectedBookType.value = savedData.type;
      }
      
      // 更新表单数据
      const fieldsToRestore = [
        'title',
        'subject',
        'grade',
        'price',
        'purchaseDiscount',
        'salesDiscount',
        'channel'
      ];
      
      fieldsToRestore.forEach(field => {
        if (savedData[field] !== undefined && savedData[field] !== null) {
          if (['price', 'purchaseDiscount', 'salesDiscount'].includes(field)) {
            bookForm[field] = Number(savedData[field]);
          } else {
            bookForm[field] = savedData[field];
          }
        }
      });

      // 如果是教辅类型，确保科目和年级正确加载
      if (selectedBookType.value === '教辅') {
        if (savedData.subject) bookForm.subject = savedData.subject;
        if (savedData.grade) bookForm.grade = savedData.grade;
      }
    }

    // 等待一下以确保所有组件都加载完成
    await nextTick();
  } catch (error) {
    console.error('初始化失败:', error);
    ElMessage.error('页面初始化失败');
  } finally {
    pageLoading.value = false; // 结束加载
  }
});

async function checkBookExists() {
  if (bookForm.isbn) {
    try {
      const response = await BookService.getBookByISBN(bookForm.isbn);
      if (response.data) {
        existingBook.value = response.data;
        dialogVisible.value = true;
      }
    } catch (error) {
      console.error("检查图书是否存在时出错:", error);
      titleInput.value.focus();
    }
  }
}

async function submitAdditionalQuantity() {
  try {
    const updatedQuantity = existingBook.value.quantity + additionalQuantity.value;
    const updatedBook = {
      ...existingBook.value,
      quantity: updatedQuantity,
      purchase_discount: existingBook.value.purchase_discount || null,
      sales_discount: existingBook.value.sales_discount || null,
      notes: existingBook.value.notes || null,
      publish_date: existingBook.value.publish_date || null,
      version: existingBook.value.version || null,
    };

    await BookService.updateBook(existingBook.value.id, updatedBook);
    dialogVisible.value = false;

    ElMessage({
      message: `已成功更新库存。当前库存为 ${updatedQuantity} 本。`,
      type: 'success',
      duration: 3000,
    });
  } catch (error) {
    console.error("更新图书数量失败:", error);
    ElMessage({
      message: '更新库存失败',
      type: 'error',
      duration: 3000,
    });
  }
}

function submitForm() {
  if (bookFormDom.value) {
    bookFormDom.value.validate(async (valid) => {
      if (valid) {
        pageLoading.value = true;
        try {
          const subject = bookForm.subject ? bookForm.subject : '';
          const grade = bookForm.grade ? bookForm.grade : '';
          const originalTitle = bookForm.title;
          
          // 设置表单数据
          bookForm.title = originalTitle;
          bookForm.subject = subject;
          bookForm.grade = grade;
          bookForm.type = selectedBookType.value;  // 设置图书类型

          const formData = Object.assign({}, bookForm);
          
          localStorage.setItem(STORAGE_KEY, JSON.stringify({
            type: selectedBookType.value,
            title: originalTitle,
            subject: bookForm.subject,
            grade: bookForm.grade,
            price: bookForm.price,
            purchaseDiscount: bookForm.purchaseDiscount,
            salesDiscount: bookForm.salesDiscount,
            channel: bookForm.channel
          }));
          
          await addBook(formData);
        } finally {
          pageLoading.value = false;
        }
      } else {
        console.log('表单验证失败');
        return false;
      }
    });
  }
}

function resetForm() {
  if (bookFormDom.value) {
    bookFormDom.value.resetFields();
    // 清除 localStorage 中的数据
    localStorage.removeItem(STORAGE_KEY);
  }
}

async function addBook(book) {
  try {
    const response = await BookService.addBook(book);
    if (response.data.success) {
      ElMessage({
        message: `${response.data.message}：《${response.data.data.title}》`,
        type: 'success',
        duration: 3000
      });
      bookForm.isbn = ''; // 添加成功后清空isbn字段
    } else {
      ElMessage({
        message: response.data.message || '添加图书失败',
        type: 'error',
        duration: 3000
      });
    }
  } catch (error) {
    console.error("添加图书失败:", error);
    ElMessage({
      message: error.response?.data?.message || '添加图书失败',
      type: 'error',
      duration: 3000
    });
  }
}

async function updateBookType(type) {
  pageLoading.value = true;
  try {
    selectedBookType.value = type;
    await nextTick();
  } finally {
    pageLoading.value = false;
  }
}

function isSelected(type) {
  return selectedTypes.value.includes(type);
}

</script>

<style>
/* 样式部分保持不变 */
</style>

